package handler

import (
	"github.com/gin-gonic/gin"
	"log"
	"math/rand"
	"onerk4/zk1/api/enit/request"
	"onerk4/zk1/api/enit/response"
	"onerk4/zk1/dao"
	"onerk4/zk1/pkg"
	"onerk4/zk1/utils"
)

func UserLogin(c *gin.Context) {
	var req request.UserLogin
	if err := c.ShouldBind(&req); err != nil {
		response.ErrorResponse(c, "参数错误", err.Error())
		return
	}
	mobile := utils.VerifyMobile(req.Mobile)
	if !mobile {
		response.ErrorResponse(c, "手机号格式不正确", nil)
		return
	}
	sms, err := dao.GetSms(req.Mobile, "Login")
	if err != nil {
		return
	}
	if sms != req.Sms {
		response.ErrorResponse(c, "验证码错误", nil)
		return
	}
	byMobile, err := dao.QueryUserByMobile(req.Mobile)
	if err != nil {
		log.Println("用户查询失败")
		return
	}
	if byMobile.Password != req.Passwd {
		response.ErrorResponse(c, "密码错误", nil)
		return
	}
	claims := pkg.CustomClaims{ID: uint(byMobile.Id)}
	token, err := pkg.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		log.Println("token生成失败")
		return
	}
	response.SuccessResponse(c, "登入成功", token)
}

func SendSms(c *gin.Context) {
	var req request.SendSms

	if err := c.ShouldBind(&req); err != nil {
		response.ErrorResponse(c, "参数错误", err.Error())
		return
	}

	code := rand.Intn(9999 + 100)

	//_, err := pkg.SendSms(req.Mobile, strconv.Itoa(code))
	//if err != nil {
	//	return
	//}

	err := dao.SetSms(req.Mobile, req.Source, code)
	if err != nil {
		response.ErrorResponse(c, "存入失败", err.Error())
		return
	}

	sms, err := dao.GetSms(req.Mobile, req.Source)
	if err != nil {
		return
	}

	response.SuccessResponse(c, "发送成功", sms)
}
